package com.martin.lib_base.ktx

import androidx.recyclerview.widget.RecyclerView
import com.martin.lib_base.common.CommonAdapter
import com.martin.lib_base.interfaces.IAdapter
import com.martin.lib_base.interfaces.IOnItemClickListener

/**
 * @author：Houge
 * @date：2022/11/11
 * @desc：RecyclerView拓展
 */

/**
 * 获取自定义适配器
 */
fun RecyclerView.commonAdapter(): CommonAdapter? {
    if (adapter == null) {
        return null
    }
    return if (this.adapter is CommonAdapter) this.adapter as CommonAdapter else null
}

/**
 * 刷新数据
 */
fun RecyclerView.refresh(items: List<Any>?) {
    // View.post，是为了等待View加载完成，并且保证执行在主线程
    post {
        adapter?.let {
            if (it is IAdapter) {
                it.refresh(items)
            }
        }
    }
}

/**
 * 加载更多数据
 */
fun RecyclerView.loadMore(items: List<Any>?) {
    post {
        adapter?.let {
            if (it is IAdapter) {
                it.loadMore(items)
            }
        }
    }
}

/**
 * 添加条目点击事件
 */
fun RecyclerView.addOnItemClickListener(listener: IOnItemClickListener) {
    post {
        commonAdapter()?.addOnItemClickListener(listener)
    }
}

/**
 * 获取条目数据
 */
fun RecyclerView.getItem(position: Int): Any? {
    return commonAdapter()?.getItem(position)
}

/**
 * 设置条目数量
 */
fun RecyclerView.setItemCount(count : Int) {
    post {
        adapter?.let {
            if (it is CommonAdapter) {
                it.setItemCount(count)
            }
        }
    }
}